package chaoyue.study.factory;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局过滤
 * 这边以参数打印为例子
 */
@Slf4j
@Component
public class LogPrintGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        String path = exchange.getRequest().getURI().getPath();
        log.info("请求：{}, 参数：{}", path, queryParams);
        // 其实通过判断是否调用下面逻辑可以中断调用链 比如直接return exchange.getResponse().setComplete();
        // 所以其实过滤器也可以实现鉴权操作（代替Predicate的作用）
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
